const { userM } = require('../models');

module.exports = (app, secret, jwt, errors, crypto) => {
    //用户注册
    app.post('/user/reg', async (req, res, next) => {
        try {
            const {
                username
            } = req.body;
            const isUserExist = await userM.count({
                username
            })
            if (isUserExist > 0) {
                res.send({
                    code: 'error',
                    msg: '用户已经存在了!',
                    data: {}
                })
            } else {
                const user = new userM(req.body)
                user.token = '';
                user.password = crypto.createHash('md5').update(user.password).digest('hex')
                user.info = {
                    nick: '',
                    avator: '',
                    status: '',
                    lastLoginIp: '',
                    lastLoginTime: '',
                    creatorId: '',
                    createTime: '',
                    deleted: '',
                    menuList: [],
                    role: {
                        id: {},
                        username: '',
                        status: '',
                        actionList: '',
                        deleted: '',
                        permissions: '',
                    }
                };
                await user.save()
                res.send({
                    code: '200',
                    msg: '注册成功',
                    data: {}
                })
            }
        } catch (error) {
            res.send(new errors.InternalServerError(error))
        }
        next();
    })
    //用户登录
    app.post('/auth/login', async (req, res, next) => {
        try {
            const { password, username } = req.body;
            const user = await userM.findOne({ username })
            const token = jwt.sign({
                userId: user._id,
            }, secret);
            await userM.findOneAndUpdate(
                { username: username },
                {
                    $set: {
                        token: token
                    }
                })
            if (user) {
                if (user.password == password) {
                    user.token = token;
                    res.send({
                        code: 200,
                        msg: '登陆成功',
                        result: {
                            token: token
                        },
                    })
                } else {
                    res.send({
                        code: '404',
                        msg: '密码错误',
                        result: {},
                    })
                }
            } else {
                res.send({
                    code: '404',
                    msg: '用户不存在',
                    result: {},
                })
            }
        } catch (error) {
            res.send(new errors.InternalServerError(error))
        }
        next();
    })
    //用户信息
    app.get('/user/info', async (req, res, next) => {
        try {
            const token = req.headers.authorization.split(' ')[1];
            jwt.verify(token, secret)
            const user = await userM.findOne({ token });
            res.send({
                code: 200,
                msg: "获取用户信息成功",
                result: {
                    "avatar": user.info.avator,
                    "status": user.info.status,
                    "lastLoginIp": user.info.creatorId,
                    "createTime": user.info.createdAt,
                    "deleted": user.info.deleted,
                    "role": {
                        "id": user.info.role.id,
                        "username": user.info.role.name,
                        "status": user.info.role.status,
                        "actionList": user.info.role.actionList,
                        "deleted": user.info.role.deleted,
                        "permissions": [user.info.role.permissions[0]]
                    }
                }
            })
        } catch (error) {
            res.send(new errors.InternalServerError(error))
        }
        next();
    })
    app.get('/user/nav', async (req, res, next) => {
        try {
            const token = req.headers.authorization.split(' ')[1];
            jwt.verify(token, secret)
            const user = await userM.findOne({ token });
            user.menu = []
            const len = user.info.menuList.length
            for (let i = 0; i < len; i++) {
                const menu = await userM.findOne({ name: user.info.menuList[i] });
                user.menu[i] = menu;
            }
            res.send({
                code: 200,
                message: "获取用户菜单成功",
                result: user.menu
            });
        } catch (error) {
            res.send(new errors.InternalServerError(error))
        }
        next()
    })
    app.post('/auth/logout', (req, res, next) => {
        return ({}, '[测试接口] 注销成功')
    })
}